#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "common.h"

const char* currentFilePos = "/mnt/usr/log/currentFilePos";
const char* importantLog = "/mnt/usr/log/importantLog.log";
#define MAX_FILE_SIZE (1024*1024)  
void saveImportantLog(const char *log)
{
    if (access(currentFilePos, F_OK) != 0)
    {
        printf("file do not exist so create file \n");
        system("touch /mnt/usr/log/currentFilePos");
    }
    if (access(importantLog, F_OK) != 0 )
    {
        system("touch /mnt/usr/log/importantLog.log");
    } 
    FILE *posFd = fopen(currentFilePos, "rt+");
    if (posFd == NULL)
    {
        printf("can not get file pos \n");
        return;
    }
    char posNum[16] = {0};
    fread(posNum, 1, 15, posFd);
    int32_t filePos = atoi(posNum);
    FILE *fd = fopen(importantLog, "rt+");
    if (fd == NULL)
    {
        printf("can not open log file \n");
        return;
    }
    const int32_t timeBufferSize = 64;
    char timeBuffer[timeBufferSize];
    
    time_t currentTime;
    time(&currentTime);
    strftime(timeBuffer, timeBufferSize, "%Y/%m/%d %Z %H:%M:%S", localtime(&currentTime));
    char buf[1024] = {0};
    sprintf(buf, "%s  %s\n", timeBuffer, log);

    fpos_t pos;
    pos.__pos = filePos;
    fsetpos(fd, &pos);
    filePos += (strlen(buf));
    if (filePos >= MAX_FILE_SIZE)
    {
        if (fseek(fd, 0, SEEK_SET) == -1)
        {
            printf("can not fseek file \n");
        }
        else
        {
            printf("set fseek to start success \n");
        }
        filePos = (strlen(buf));
    }
    fprintf(fd, "%s", buf);
    fflush(fd);
    rewind(posFd);
    fprintf(posFd, "%015d", filePos);
    fflush(posFd);
    fclose(fd);
    fclose(posFd);
    return;
}

